package ar.uba.tleng.g99.expregs;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if (args.length < 2) {
			System.out
					.println("Parametros: expresion_regular archivo_de_busqueda");
			return;
		}
		System.out.println("# Buscando [" + args[0] + "] en [" + args[1] + "]");
		G99Matcher matcher = null;
		try {
			matcher = new G99Matcher(crearSigma(), args[0]);
		} catch (G99RegexpException e) {
			System.out.println("# Error: la regexp introducida no es valida");
			return;
		}
		// Crea el linematcher.
		LineMatcher lineMatcher = new LineMatcher(matcher,
				new LineMatcherListener() {
					@Override
					public void onMatch(int lineNumber, String line) {
						System.out.println(line);
					}
				});
		// Llamar al lineMatcher.
		callLineMatcher(args[1], lineMatcher);
	}

	private static void callLineMatcher(String filename, LineMatcher lineMatcher) {
		FileInputStream fstream = null;
		try {
			fstream = new FileInputStream(filename);
		} catch (FileNotFoundException e) {
			System.out
					.println("# Error: no se encontro el archivo: " + filename);
			return;
		}
		DataInputStream in = new DataInputStream(fstream);
		try {
			lineMatcher.match(new InputStreamReader(in));
		} catch (IOException e) {
			System.out
					.println("# Error: IOException se lanzo al leer el archivo. "
							+ e.getMessage());
			return;
		}
		try {
			fstream.close();
		} catch (IOException e) {
			System.out
			.println("# Error: IOException se lanzo al cerrar el archivo. "
					+ e.getMessage());
			return;
		}
	}

	/**
	 * Sigma usado por expregs.
	 * 
	 * @return el conjunto de caracteres.
	 */
	public static Set<Character> crearSigma() {
		Set<Character> sigma = new HashSet<Character>();
		for (char c = 'a'; c <= 'z'; c++) {
			sigma.add(c);
		}
		for (char c = 'A'; c <= 'Z'; c++) {
			sigma.add(c);
		}
		for (char c = '0'; c <= '9'; c++) {
			sigma.add(c);
		}
		sigma.add(' ');
		return sigma;
	}

}
